package org.jackysoft.controller;

import java.io.BufferedOutputStream;
import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jackysoft.controller.base.AbstractController;
import org.jackysoft.entity.ActionNode;
import org.jackysoft.entity.OfficeDataValue;
import org.jackysoft.entity.OfficeDocument;
import org.jackysoft.service.OfficeDataRegionService;
import org.jackysoft.service.OfficeDocumentService;
import org.jackysoft.service.OsWorkflowRunnerService;
import org.jackysoft.service.WorkflowNodeService;
import org.jackysoft.util.FileDownload;
import org.jackysoft.util.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.common.collect.Lists;
import com.zhuozhengsoft.pageoffice.BorderStyleType;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.wordreader.DataRegion;
import com.zhuozhengsoft.pageoffice.wordwriter.WordDocument;

@Controller
@RequestMapping("/officedocument")
public class OfficeDocumentController extends
AbstractController<OfficeDocument> {
	@Resource
	private OfficeDocumentService service;	

	private @Resource
	OfficeDataRegionService dataService;

	@Resource
	WorkflowNodeService nodeService;
	
	
	@Resource
	OsWorkflowRunnerService wfrunnerService;

	
	@RequestMapping("/viewdoc/{refid}")
	public void viewdoc(
			@PathVariable  long refid,
			@ModelAttribute String openUrl,
			HttpServletResponse response
			) throws Exception {
		
		openUrl = String.format("admin/office/office-manager!viewdoc?workflowId=%d", refid);
		
		FileDownload fd = service.downloadByRefid(refid);
		response.reset();  
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fd.getTitle() + "\"");  
		response.addHeader("Content-Length", "" +fd.getDataSize());  
		response.setContentType("application/octet-stream;charset=UTF-8");  
		BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		IOUtils.copyLarge(fd.getInputStream(), outputStream);
		outputStream.flush();  
		outputStream.close(); 
		
		
	}
	
	/**
	 * 保存office的内容
	 */
	@RequestMapping("/save/{refid}")
	public void savedoc(
			@PathVariable long refid,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		FileSaver fs = new FileSaver(request, response);		
		service.saveDoc(refid,fs);
		request.setAttribute("fs", fs);		
	}

	public String viewoffice(long workflowId,int actionId,String refname,String openUrl, OpenModeType openModeType,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath()
				+ "/";
		WordDocument doc = new WordDocument();

		PageOfficeCtrl poCtrl1 = new PageOfficeCtrl(request);

		Collection<OfficeDataValue> tags = dataService.findAllByRefid(workflowId);
		for (OfficeDataValue tag : tags) {

			com.zhuozhengsoft.pageoffice.wordwriter.DataRegion dr = doc
					.openDataRegion(tag.getName());
			dr.setEditing(true);
			log.debug(String.format("workflow:%d dataregion %s editable is %s",
					workflowId, dr.getName(), dr.getEditing()));

		}
		poCtrl1.setServerPage(basePath + "poserver.do"); // 此行必须
		// 设置界面样式
		poCtrl1.setCaption("庆华公司文件审批模版");
		poCtrl1.setBorderStyle(BorderStyleType.BorderThin);
		// 添加自定义工具条按钮
		poCtrl1.addCustomToolButton("返回", "poPrev()", 3);
		poCtrl1.addCustomToolButton("保存并提交", "poSave()", 1);
		poCtrl1.addCustomToolButton("直接提交", "poNext()", 6);
		ActionNode an = nodeService.getActionNode(actionId,refname);
		boolean readonly = openModeType != OpenModeType.docReadOnly;
		if (openModeType != OpenModeType.docReadOnly) {
			poCtrl1.setJsFunction_AfterDocumentSaved("afterSave()");
			openModeType = an.isStart() ? OpenModeType.docNormalEdit
					: OpenModeType.docRevisionOnly;
		}
		// 隐藏工具栏
		poCtrl1.setOfficeToolbars(readonly);
		poCtrl1.setCustomRibbon("ribbon");
		poCtrl1.setMenubar(readonly);
		// 设置保存文档的服务器页面
		refname = wfrunnerService.findRunneRefname(workflowId);
		poCtrl1.setSaveDataPage(basePath
				+ "workflow/document/document!savemeta?workflowId="
				+ workflowId);
		poCtrl1.setSaveFilePage(basePath
				+ "admin/office/office-manager!savedoc?workflowId="
				+ workflowId);

		poCtrl1.setWriter(doc);
		// 打开文档
		// poCtrl1.webOpen("law-contract!openstream",
		// OpenModeType.docSubmitForm,"Tom");
		Object owner = org.apache.shiro.SecurityUtils.getSubject();

		poCtrl1.webOpen(basePath + openUrl, openModeType, owner.toString());

		poCtrl1.setTagId("PageOfficeCtrl1"); // 此行必须

		return "viewoffice";
	}
	
	
	public String savemeta(long workflowId, OpenModeType openModeType,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		com.zhuozhengsoft.pageoffice.wordreader.WordDocument doc = new com.zhuozhengsoft.pageoffice.wordreader.WordDocument(
				request, response);
		ArrayList drs = doc.getDataRegions();
		Collection<OfficeDataValue> tags = Lists.newArrayList();
		String processName = wfrunnerService.findRunneRefname(workflowId);
		for (Object o : drs) {
			DataRegion dr = (DataRegion) o;
			log.info("data region : " + dr.getName() + "=>" + dr.getValue());
			tags.add(new OfficeDataValue("PO_" + dr.getName(), dr.getValue(),
					processName, workflowId));
		}
		
		dataService.removeByRefid(workflowId);
		dataService.save(tags);
		request.setAttribute("doc", doc);
		return "savedocmeta";
	}

}